<template>
  <div id="s">
    <!--  分隔-->

    <el-row>
      <el-col :span="24">
        <div class="grid-content bg-purple-light">
          <div style="float: right; margin-top: 2px;margin-right: 50px">
            <el-button size="info" @click="back" plain>返回</el-button>
            <el-button size="info" @click="save" :disabled="closeButton" plain>确认</el-button>
          </div>
          <div class="separate">&nbsp;&nbsp;&nbsp;&nbsp;<i class="el-icon-s-data"></i>基本信息</div>
        </div>
      </el-col>
    </el-row>
    <!--  查询条件-->

    <el-form :inline="true" :model="invoice" :rules="rules" ref="ruleForm"
             label-width="150px" :label-position="'right'" style="text-align: left">
      <el-row type="flex" class="row-bg">
        <el-col :span="8">
          <el-form-item label="发票号" prop="invoiceId">
            <el-input v-model="invoice.invoiceId" placeholder="发票号" clearable></el-input>
          </el-form-item>
          <el-form-item label="发票抬头" prop="invoiceHeader">
            <el-input v-model="invoice.invoiceHeader" placeholder="抬头" clearable></el-input>
          </el-form-item>
          <el-form-item label="录入人员">
            <el-input v-model="invoice.createUser" placeholder="录入人员" readonly clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="委托客户" prop="client">
            <el-input v-model="invoice.client" placeholder="委托客户" suffix-icon="el-icon-search"
                      @click.native="showClients()" readonly></el-input>
          </el-form-item>
          <el-form-item label="税率%" prop="tax">
            <el-input v-model="invoice.tax" placeholder="税率" clearable></el-input>
          </el-form-item>
          <el-form-item label="录入时间">
            <el-input v-model="invoice.createTime" placeholder="录入时间" readonly clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="含税总额(元)" prop="total">
            <el-input v-model="invoice.total" placeholder="含税总额" clearable></el-input>
          </el-form-item>
          <el-form-item label="税号" prop="taxId">
            <el-input v-model="invoice.taxId" placeholder="税号" clearable></el-input>
          </el-form-item>
          <el-form-item label="客户电话" prop="clientPhone">
            <el-input v-model="invoice.clientPhone" placeholder="客户电话" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="注册地址" prop="clientAddr">
            <el-input v-model="invoice.clientAddr" placeholder="注册地址" clearable></el-input>
          </el-form-item>
          <el-form-item label="开户行" prop="bankName">
            <el-input v-model="invoice.bankName" placeholder="开户行" clearable></el-input>
          </el-form-item>
          <el-form-item label="银行账号" prop="bankAccount">
            <el-input v-model="invoice.bankAccount" placeholder="银行账号" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!--  客户查询-->
    <el-dialog
      title="客户"
      :visible.sync="showClient"
      width="50%">
      <div slot="footer" class="dialog-footer">
        <!--  查询条件-->
        <el-form :inline="true" :model="queryClient" style="text-align: left">
          <el-form-item label="客户编号">
            <el-input v-model="queryClient.orderCustomerId" placeholder="" clearable></el-input>
          </el-form-item>
          <el-form-item label="客户名称">
            <el-input v-model="queryClient.customerName" placeholder="" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getClient">查询</el-button>
          </el-form-item>
        </el-form>
        <!--  数据表格-->
        <el-table :data="clients" style="width: 100%" :border="true" highlight-current-row
                  @current-change="handleCurrentChange" :header-cell-style="{background:'#f7f7f7', color:'#666666'}">
          <el-table-column
            type="index"
            label="序号"
            width="50">
          </el-table-column>
          <el-table-column
            prop="customerId"
            label="客户编号"
            width="200">
          </el-table-column>
          <el-table-column
            prop="customerName"
            label="客户公司全称">
          </el-table-column>
        </el-table>
        <!--  分页-->
        <div style="width: 65%;">
          <el-pagination
            @size-change="getClient"
            @current-change="getClient"
            :current-page.sync="queryClient.pageNum"
            :page-sizes="[10, 20, 30, 40, 60, 80, 100]"
            :page-size.sync="queryClient.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="clientTotal">
          </el-pagination>
        </div>
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
    <!--  分隔-->
    <el-row>
      <el-col :span="24">
        <div class="grid-content bg-purple-light">
          <div style="float: right; margin-top: 2px;margin-right: 50px">
            <el-button size="info" @click="addStatement" plain>添加对账单</el-button>
          </div>
          <div class="separate">&nbsp;&nbsp;&nbsp;&nbsp;<i class="el-icon-s-grid"></i>对账单</div>

        </div>
      </el-col>
    </el-row>
    <!--  订单表格-->
    <el-table :data="invoice.statements" show-summary :summary-method="getSummaries"
              :header-cell-style="{background:'#f7f7f7', color:'#666666'}">
      <el-table-column
        type="index"
        label="序号">
      </el-table-column>
      <el-table-column
        prop="statementId"
        label="对账单编号">
      </el-table-column>
      <el-table-column
        prop="client"
        label="委托客户">
      </el-table-column>
      <el-table-column
        prop="total"
        label="订单金额(元)">
      </el-table-column>
      <el-table-column
        prop="checkedMoney"
        label="已收金额(元)">
      </el-table-column>
      <el-table-column
        prop="checked"
        label="是否对账">
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="录入时间">
      </el-table-column>
      <el-table-column
        label="操作">
        <template v-slot="scope">
          <el-popconfirm title="确定删除吗？" @confirm="remove(scope.row)">
            <el-button slot="reference" type="text" size="small">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--  订单查询-->
    <el-dialog
      title="对账单"
      :visible.sync="showStatement"
      width="50%">
      <div slot="footer" class="dialog-footer">
        <!--  查询条件-->
        <el-form :inline="true" :model="queryStatement" style="text-align: left">
          <el-form-item label="对账单号">
            <el-input v-model="queryStatement.statementId" placeholder="对账单号" clearable></el-input>
          </el-form-item>
          <el-form-item label="委托客户">
            <el-input v-model="invoice.client" readonly></el-input>
          </el-form-item>
          <el-form-item label="是否对账">
            <el-select v-model="queryStatement.checked" clearable placeholder="请选择">
              <el-option value='是'></el-option>
              <el-option value='否'></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getList">查询</el-button>
          </el-form-item>
        </el-form>
        <!--  表格-->
        <el-table :data="statements" :header-cell-style="{background:'#f7f7f7', color:'#666666'}"
                  ref="multipleTable" @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            type="index"
            label="序号">
          </el-table-column>
          <el-table-column
            prop="statementId"
            label="委托单编号">
          </el-table-column>
          <el-table-column
            prop="client"
            label="委托客户">
          </el-table-column>
          <el-table-column
            prop="total"
            label="对账单金额(元)">
          </el-table-column>
          <el-table-column
            prop="checkedMoney"
            label="已收金额(元)">
          </el-table-column>
          <el-table-column
            prop="checked"
            label="是否对账">
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="录入时间">
          </el-table-column>
        </el-table>
        <!--  分页-->
        <div style="width: 65%;">
          <el-pagination
            @size-change="getList"
            @current-change="getList"
            :current-page.sync="queryStatement.pageNum"
            :page-sizes="[10, 20, 30, 40, 60, 80, 100]"
            :page-size.sync="queryStatement.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="statementTotal">
          </el-pagination>
        </div>
        <el-button @click="cancleStatement">取 消</el-button>
        <el-button type="primary" @click="confirmStatement">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
export default {
  name: "AddInvoice",
  data() {
    return {
      //发票表单信息
      invoice: {
        total: 0,
        statements: [],
        invoiceId: '',
        invoiceHeader: '',
        client: '',
        tax: '',
        taxId: '',
        clientPhone: '',
        clientAddr: '',
        bankName: '',
        bankAccount: ''
      },
      //校验规则
      rules: {
        client: [{required: true, message: '请选择委托客户', trigger: 'blur'}],
        invoiceId: [{required: true, message: '请输入发票号', trigger: 'blur'}],
      },
      //查询客户参数
      queryClient: {},
      clients: [],
      clientTotal: 0,
      //选定的客户
      selectClient: {},
      showClient: false,
      //对账单参数
      statements: [],
      statementTotal: 0,
      showStatement: false,
      queryStatement: {
        pageNum: 1,
        pageSize: 10,
        statementId: '',
        client: '',
        checked: '是',
        checkedInvoice: '否'
      },
      temRelaStatements: [],
      //禁用提交按钮
      closeButton: false
    }
  },
  methods: {
    //提交表单新增发票请求
    save() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.$axios({
            url: 'finance/invoice/add',
            method: 'post',
            data: this.invoice
          }).then(res => {
            if (res.data.success) {
              this.closeButton = true
              this.$message.success(res.data.message);
            } else {
              this.$message.error(res.data.message)
            }
          }).catch(err => {
            this.$message.error(err.message);
          })
        }
      })
    },
    //显示查询客户窗口
    showClients() {
      this.showClient = true;
      this.getClient();
    },
    //查询客户请求
    getClient() {
      this.$axios({
        url: 'base/customer/getList',
        method: 'post',
        data: this.queryClient
      }).then(res => {
        if (res.data.success) {
          this.clients = res.data.object.list;
          this.clientTotal = res.data.object.total;
        } else {
          this.$message.error(res.data.message)
        }
      }).catch(err => {
        this.$message.error(err.message);
      })

    },
    //取到选定的客户
    handleCurrentChange(val) {
      this.selectClient = val;
    },
    //选定的客户赋给查询条件
    confirm() {
      if (this.selectClient != null) {
        //切换客户，赋值为空
        this.invoice.statements = []
        this.invoice.client = this.selectClient.customerName;
        this.queryStatement.client = this.selectClient.customerName
      }
      this.showClient = false;
      this.$refs['ruleForm'].clearValidate('client')
    },
    //清空查询条件，关闭对话框
    cancle() {
      this.invoice.client = '';
      this.showClient = false;
    },
    //对账单相关操作
    //查询对账单列表请求
    getList() {
      this.$axios({
        url: 'finance/statement/getList',
        method: 'post',
        data: this.queryStatement
      }).then(res => {
        if (res.data.success) {
          this.statements = res.data.object.list;
          this.statementTotal = res.data.object.total;
        } else {
          this.$message.error(res.data.message)
        }
      }).catch(err => {
        this.$message.error(err.message);
      })
    },
    //显示增加对账单窗口
    addStatement() {
      //判断是否选择客户，未选择提示选择
      if (this.invoice.client != '') {
        this.temRelaStatements = [];
        this.$refs.multipleTable.clearSelection();
        this.showStatement = true;
        this.getList();
      } else {
        this.$message.info("请选择委托客户")
      }
    },
    //取消选择，关闭选择窗口
    cancleStatement() {
      this.temRelaStatements = [];
      this.showStatement = false;
    },
    //确认选择，添加对账单
    confirmStatement() {
      //判断对账单是否已存在，已存在不允许添加
      for (let statement of this.temRelaStatements) {
        for (let relaStatement of this.invoice.statements) {
          if (statement.statementId == relaStatement.statementId) {
            this.$message.info('对账单重复，添加失败')
            return
          }
        }
        this.invoice.statements.push(statement);
      }
      this.showStatement = false;
    },
    //选择赋给中间参数
    handleSelectionChange(val) {
      this.temRelaStatements = val;
    },
    //删除对账单，为空时将计算属性赋0
    remove(row) {
      this.invoice.statements.splice(this.invoice.statements.indexOf(row), 1)
      if (this.invoice.statements.length == 0) {
        this.invoice.total = 0;
      }
    },
    //返回到上一个界面
    back() {
      this.$router.back();
    },
    //表格中新增统计行规则
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总价';
          return;
        } else if (index != 3) {
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              if (column.property == 'total') {
                //将计算的值赋给指定表单
                this.invoice.total = prev + curr;
              }
              return prev + curr;
            } else {
              //将计算的值赋给指定表单
              if (column.property == 'total') {
                this.invoice.total = prev;
              }
              return prev;
            }
          }, 0);
        } else {
        }
      });
      return sums;
    }

  },
  created() {
    //生成录入人员时间
    this.invoice.createTime = new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate()
    this.invoice.createUser = this.$store.state.loginUserName
  }
}
</script>

<style scoped>

.bg-purple-light {
  background: rgb(237, 237, 237);
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
  margin-bottom: 15px;
}

/deep/ .el-table .el-table__body td .cell:empty::after,
.el-table .el-table__body td .cell > span:empty::after,
.el-table .el-table__body td .cell .approval:empty::after,
.el-table .el-table__body td .cell div:empty::after,
.el-table .el-table__body td .cell .line-limit-length:empty::after {
  content: "--";
}

#s {
  width: 90%;
  margin: 10px auto;
  background-color: #ffffff;
  box-shadow: 10px 10px 5px #c4c6c7;
  border-radius: 5px
}

.el-button--info:hover {
  background: #209e91;
  border-color: #209e91;
  color: #FFF;
}

.separate {
  width: 100%;
  height: 50px;
  background: #339999;
  border-color: #339999;
  text-align: left;
  line-height: 50px;
  color: #FFFFFF;
}
</style>
<style>
.el-table .warning-row {
  background: oldlace !important;
}

.el-table__body tr.current-row > td {
  background-color: rgba(65, 225, 105, 0.45) !important;
}

</style>
